import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('开关、复选框、单选框组件'),
        ),
        body: CheckboxAndSwitchWidget(),
      ),
    );
  }
}

class CheckboxAndSwitchWidget extends StatefulWidget {
  @override
  _CheckboxAndSwitchWidgetState createState() =>
      _CheckboxAndSwitchWidgetState();
}

class _CheckboxAndSwitchWidgetState extends State<CheckboxAndSwitchWidget> {
  bool _cbSelected = false;
  bool _switchSelected = false;
  var _groupValue;
  int sex = 1;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Checkbox(
            value: _cbSelected,
            onChanged: (value) {
              setState(() {
                _cbSelected = value;
              });
            }),
        Switch(
            value: _switchSelected,
            onChanged: (value) {
              setState(() {
                _switchSelected = value;
              });
            }),
        // 带描述的switch
        SwitchListTile(
          value: true,
          onChanged: (value) {},
          title: Text('兴趣'),
          subtitle: Text('是否感兴趣'),
          secondary: Icon(Icons.remove_red_eye_sharp),
        ),
        Row(
          children: [
            // Radio数组为互斥关系
            Radio(
                activeColor: Colors.redAccent,
                value: 'op1',
                groupValue: _groupValue,
                onChanged: (value) {
                  setState(() {
                    _groupValue = value;
                  });
                }),
            Radio(
                value: 'op2',
                activeColor: Colors.green,
                groupValue: _groupValue,
                onChanged: (value) {
                  setState(() {
                    _groupValue = value;
                  });
                })
          ],
        ),
        RadioListTile(
            value: 1,
            groupValue: this.sex,
            title: Text("是一个男孩子"),
            secondary: Text("是否为男孩"),
            //选中后，改变radio和文本
            selected: this.sex == 1,
            onChanged: (v) {
              setState(() {
                this.sex = v;
              });
            }),
        SizedBox(height: 10),
        RadioListTile(
            value: 2,
            groupValue: this.sex,
            title: Text("是一个女孩子"),
            secondary: Text("是否为女孩"),
            selected: this.sex == 2,
            onChanged: (v) {
              setState(() {
                this.sex = v;
              });
            }),
      ],
    );
  }
}
